<script setup>
    import {ref, reactive} from 'vue'
    import {Search, ShoppingCart, Minus, Plus, Shop, Close, Delete} from "@element-plus/icons-vue";
    import {cartAddService, cartUpdateService} from "@/api/shoppingcart";
    import {categoryListService} from "@/api/good";
    import {addNewOrderService} from "@/api/order";

    const gcId = ref(null)
    const gName = ref('')
    //存放商品分类
    const navData = ref([
        {id: 1, name: "女装"},
        {id: 2, name: "男装"},
    ])
    //商品分类列表
    const categoryList = async () => {
        let result = await categoryListService();
        console.log(result.data)
        if (result.data != null) {
            navData.value = result.data.map(item => ({
                id: item.gcId,
                name: item.gcName,
            }))
        } else {
            ElMessage.error("商品分类列表出现问题")
        }
    }
    categoryList();
    //分类点击事件处理
    const onCategoryClick = (categoryId) => {
        gcId.value = categoryId;
        goodsList()
    }

    const goods = ref([])
    //获取商品列表数据
    import {goodsListService} from "@/api/good";
    import {ElMessage} from "element-plus";

    const goodsList = async () => {
        let params = {
            gcId: gcId.value ? gcId.value : null,
            gName: gName.value ? gName.value : null
        }
        let result = await goodsListService(params);
        if (result.data != null) {
            goods.value = result.data.map(item => ({
                g_id: item.gid,
                g_img: item.gimg,
                g_unitPrice: item.gunitprice,
                g_name: item.gname,
                soldCount: item.soldcount,
                g_details: item.gdetails,
                s_username: item.snickname
            }))
        } else {
            ElMessage("搜索结果为空")
        }
    }
    goodsList()

    const visibleDetail = ref(false)
    const payDialogVisible = ref(false);
    // 当前选中的商品详情
    const currentDetail = ref({
        g_id: '',
        g_name: '',
        g_img: '',
        s_name: '',
    });
    // 当前选择的商品数量
    const currentQuantity = ref(1);
    // 加入购物车时显示的商品ID和数量
    const cartItemId = ref(null);
    const cartQuantity = ref(1);
    // 立即支付时显示的商品ID、数量和金额
    const payItemId = ref(null);
    const payItemName = ref('');
    const payQuantity = ref(1);
    const payAmount = ref(0);

    // 显示抽屉
    function showDetail(item) {
        visibleDetail.value = true;
        currentDetail.value = item;
        payAmount.value = currentDetail.value.g_unitPrice * currentQuantity.value;
    }

    // 添加到购物车
    const addToCart = async () => {
        cartItemId.value = currentDetail.value.g_id; // 商品的id属性
        cartQuantity.value = currentQuantity.value;
        if(Number.isInteger(cartQuantity.value) && cartQuantity.value >= 1 && cartQuantity.value <= 99){
            let params = {
                g_id: cartItemId.value,
                g_count: cartQuantity.value
            }
            let result = await cartAddService(params)
            ElMessage.success(result.msg ? result.msg : "添加成功");
            currentQuantity.value = 1;
            visibleDetail.value = false;
            goodsList();
        }
        else{
            currentQuantity.value = 1;
        }
    }

    // 立即支付
    const payForItem = async () => {
        // payDialogVisible.value = true;
        payItemId.value = currentDetail.value.g_id; // 假设商品有id属性
        payQuantity.value = currentQuantity.value;
        payAmount.value = currentDetail.value.g_unitPrice * currentQuantity.value;
        if(Number.isInteger(payQuantity.value) && payQuantity.value >= 1 && payQuantity.value <= 99){
            // payAmount.value 已经在 showDrawer 中设置过了
            let orderForm = {
                time: new Date(),
                state: 0,
                goodsId: payItemId.value,
                goodsCount: payQuantity.value,
                orderItemAmount: payAmount.value
            }
            //接口
            let result = await addNewOrderService(orderForm);
            ElMessage.success(result.msg ? result.msg : '下单成功，可前往 我的订单 页面进行付款')
            payDialogVisible.value = false;
            visibleDetail.value = false;
            currentQuantity.value=1;
        }
        else{
            ElMessage.error('请选择1到99之间的商品数量')
            currentQuantity.value = 1;
            payDialogVisible.value = false;
        }
    }

    //取消立即支付
    const cancelOrder =() =>{
        ElMessage('您取消了支付')
        payDialogVisible.value = false;
        visibleDetail.value = false;
    }

    const imageUrls = ref([
        require('@/assets/pic1.jpg'),
        require('@/assets/pic2.jpg'),
        require('@/assets/pic3.jpg')
    ]);

    import {getHistoryList, setHistoryList} from '@/utils/storage'

    const showHistory = ref(false)//是否显示搜索历史纪录
    const historyList = ref([])//搜索历史记录的列表
    historyList.value = getHistoryList();//从本地获取搜索记录
    //搜索
    const goSearch = (key) => {
        const index = historyList.value.indexOf(key)
        if (index !== -1) {
            //存在相同的值
            historyList.value.splice(index, 1)//删除原本的值
        }
        historyList.value.unshift(key)//将搜索记录存在数组的最前面
        // 确保只保留最新的20条记录
        if (historyList.value.length > 20) {
            historyList.value = historyList.value.slice(0, 20);
        }
        setHistoryList(historyList.value)
        goodsList();
    }
    //删除历史搜索记录
    const clearHistory = () => {
        historyList.value = []
        setHistoryList([])
    }

    const handleClickOutside = (event) => {
        // 检查点击事件的目标是否在历史记录或输入框以外的区域
        if (!event.target.closest('.history_box') && !event.target.closest('.el-input')) {
            showHistory.value = false; // 点击历史记录或输入框以外的区域时隐藏历史记录
        }
    };
    import {onMounted, onUnmounted} from "vue";
    import {userInfoGetService} from "@/api/user";

    onMounted(() => {
        // 监听整个页面的点击事件
        document.addEventListener('click', handleClickOutside);
    });

    onUnmounted(() => {
        // 组件销毁前移除点击事件监听
        document.removeEventListener('click', handleClickOutside);
    });
    const selectHistory = (item) => {
        // 选中历史记录项的逻辑，这里你可以执行搜索等操作
        gName.value = item;
        showHistory.value = false;//关闭搜索历史纪录框
    };
    //数量变换
    const handleChange = (value) => {
        if (Number.isInteger(value) && value >= 1 && value <= 99) {
            console.log(value)
        } else {
            ElMessage.error("请输入1到99之间的整数")
        }
    }
    const p_address = ref(null)
    //判断地址
    let token = localStorage.getItem('token');
    // alert(token)
    if (token) {
//获取个人信息
        const getAddress = async () => {
            let result = await userInfoGetService();
            p_address.value = result.data.paddress
        }
        getAddress()
    }
    //重置搜索
    const resetSearch = () => {
        gName.value = '';
        gcId.value = '';
        goodsList();
    }
</script>
<template>
    <div id="subject">
        <!--         这是覆盖轮播图的盒子 ;-->
        <div class="block text-center" style="position: relative;">
            <div class="overlay-box">
                <div class="goodsCategory" v-for="item in navData" :key="item.id" @click="onCategoryClick(item.id)">
                    {{ item.name }}
                </div>
            </div>
            <el-carousel height="540px">
                <el-carousel-item :key="index" v-for="(image, index) in imageUrls">
                    <img :src="image" :alt="'Slide ' + (index + 1)" class="carousel-image">
                </el-carousel-item>
            </el-carousel>
        </div>
        <el-affix :offset="45" style="position: relative;">
            <div style="display:inline-block;width: 25%;"></div>
            <el-input
                    v-model="gName"
                    size="large"
                    placeholder="请输入商品名称"
                    :prefix-icon="Search"
                    clearable
                    @focus="showHistory = true"
            ></el-input>
            <el-button @click="goSearch(gName); gName=''" :disabled="!gName.trim()">
                搜索
            </el-button>
            <el-button @click="resetSearch()">
                重置
            </el-button>
            <div class="history_box" style=" z-index: 999; position: absolute;" v-if="showHistory" ref="historyBox">
                <div style="font-size: 20px;color: #8c939d;">
                    历史记录
                    <el-icon style="float: right;margin-right: 15px;margin-top: 5px" @click="clearHistory">
                        <Delete/>
                    </el-icon>
                </div>
                <div>
                    <div class="list_item" v-for="item in historyList" :key="item" @click="selectHistory(item)">
                        {{ item }}
                    </div>
                </div>
            </div>
        </el-affix>
        <div class="goodsGroup">
            <div class="goodsCard" v-for="(item,index) in goods" :key="index" @click="showDetail(item)">
                <div class="img-big">
                    <el-image :src="item.g_img" v-if="item.g_img" class="good-picture"/>
                    <el-image :src="require('@/assets/空2.png')" v-else class="good-picture"/>
                </div>
                <div class="info-big">
                    <div class="good-name" :title="item.g_name" @click.stop="showDetail(item)">{{ item.g_name }}</div>
                    <div class="money-container">
                        <div class="good-money">¥ {{ item.g_unitPrice }}</div>
                        <div class="sell-count" v-if="item.soldCount">已售 {{ item.soldCount }} 件</div>
                        <div class="sell-count" v-else>已售 0 件</div>
                    </div>
                    <div class="tag-container">
                        <span style="color: #8c939d; padding-top: 3px">
                            <el-icon>
                                <Shop/>
                            </el-icon>
                        </span>
                        <div class="tag" :title="item.s_username">{{ item.s_username }}</div>
                    </div>
                </div>

            </div>
        </div>
        <!-- 抽屉组件 -->
        <el-drawer
                title="商品详情"
                v-model="visibleDetail"
                size="80%"
                style="width: 70%;"
                direction="btt"
                :with-header="false"
        >
            <template #header="商品详情页">
                <h4 style="font-size: 20px">商品详情页</h4>
            </template>
            <!-- 抽屉内容 -->
            <div class="tag-container" style="justify-content: flex-start; align-items: flex-start">
                <div class="img-class">
                    <el-image :src="currentDetail.g_img" v-if="currentDetail.g_img" class="detail-picture"/>
                    <el-image :src="require('@/assets/空2.png')" v-else class="detail-picture"/>
                    <div style="width: 30vw; height: 80px; margin-top: 10px; padding: 5px; font-size: 20px; background-color: whitesmoke">
                        <span>{{ currentDetail.g_details }}</span></div>
                </div>
                <div class="detail-container">
                    <div class="supplier-name">
                        供应商：<span>{{ currentDetail.s_username }}</span>
                    </div>
                    <div class="good-name" style="font-weight: bold">
                        <span>{{ currentDetail.g_name }}</span>
                    </div>
                    <div class="detail-money">
                        <span style="padding-left: 10px">¥</span>
                        <span>{{ currentDetail.g_unitPrice }}</span>
                    </div>
                    <div style="margin-top: 20px">
                        <span style="color: #8c939d; font-size: 20px">配送&nbsp;&nbsp;至</span>
                        <textarea
                                style="margin-top: 10px; width: 96%; font-size: 14px; height: 32px; resize: none; overflow: auto"
                                type="text" v-model="p_address" v-if="p_address" readonly></textarea>
                        <textarea
                                style="margin-top: 10px; width: 96%; font-size: 14px; height: 32px; resize: none; overflow: auto"
                                type="text" v-else readonly>请登录后设置收货地址</textarea>
                    </div>
                    <div style="display: flex; align-items: flex-start; margin-top: 10px">
                        <div style="display: inline-block; width: 7vw; height: 6vh; line-height: 6vh; color: #8c939d">
                            数量
                        </div>
                        <el-input-number v-model="currentQuantity" :min="1" :max="99" @change="handleChange"/>
                    </div>
                    <div style="margin-top: 20px">
                        <el-button style="background-color: rgba(255,41,194,0.68);font-size: 20px;width: 140px"
                                   @click="payDialogVisible=true; payItemName=currentDetail.g_name">
                            立即下单
                        </el-button>
                        <el-button style="background-color: rgba(255,191,42,0.68);font-size: 20px;width: 140px"
                                   @click="addToCart">
                            加入购物车
                            <el-icon>
                                <shopping-cart/>
                            </el-icon>
                        </el-button>
                    </div>
                </div>
            </div>
        </el-drawer>

        <!-- 弹窗组件（立即支付） -->
        <el-dialog
                title="立即支付"
                v-model="payDialogVisible"
                width="30%"
        ><!-- 弹窗内容 -->
            您选择将<span style="color: mediumpurple">&nbsp;{{ currentQuantity }}&nbsp;</span>件商品名称为&nbsp;<span
                    style="color: mediumpurple">{{
                    payItemName
                }}</span>&nbsp;的商品下单，订单金额为&nbsp;<span
                    style="color: mediumpurple"> {{ (currentDetail.g_unitPrice * currentQuantity).toFixed(2)  }}</span>&nbsp;元
            <div style="margin-top: 20px; justify-content: space-between; display: flex">
                <el-button style="background-color: skyblue;font-size: 20px;width: 90px; margin-top: 20px"
                           @click="payForItem">
                    确定
                </el-button>
                <el-button style="background-color: darkseagreen; font-size: 20px;width: 90px; margin-top: 20px"
                           @click="cancelOrder">
                    取消
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "PurchaserHome"

    }
</script>


<style scoped>
    #subject {
        /*background-color: #57d1e6;*/
        padding-bottom: 20px;
        height: 100vh;
        overflow: auto;
    }

    /*//遮盖轮播图的盒子*/
    #subject .overlay-box {
        position: absolute;
        left: 20px;
        width: 100px;
        /*height: 291px; !* 覆盖部分的高度，根据需要调整 *!*/
        background-color: white; /* 设置背景颜色和透明度 */
        margin-top: 0px;
        height: 83vh;
        z-index: 1;
    }

    /*轮播的图片*/
    #subject .carousel-image {
        width: 100%;
        /*height: 100%;*/
        /*width: 99vw;*/
        height: 99vh;
    }

    /*搜索历史框的盒子*/
    #subject .history_box {
        position: absolute;
        /*display: inline-block;*/
        background-color: white;
        margin-left: 25%;
        height: 121px;
        width: 300px;
        border: #f13b82 1px solid;

    }

    /*每个搜索历史的小盒子*/
    #subject .list_item {
        display: inline-block;
        height: 20px;
        width: auto;
        margin-left: 8px;
        font-size: 12px;
        text-align: center;
        border: #cccccc 1px solid;
    }

    /*以下为导航栏部分*/
    #subject .nav-wrapper {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        background-color: white;
        z-index: 999; /* 一个高的z-index值以确保它位于其他内容之上 */
    }

    #subject .nav-wrapper .nav {
        flex: 1; /*导航项占据可用空间的剩余部分*/
        display: flex;
        flex-wrap: wrap; /*允许导航项换行*/
        align-items: center;
    }

    #subject .nav-wrapper .nav li {
        display: inline-block;
        height: 8vh;
        line-height: 7vh;
        padding: 0 18px;
        color: #fff;
        font-size: 13px;
        text-align: center;
        cursor: pointer;
        /*background-color: rgba(255, 106, 220, 0.68);*/
    }

    #subject .search-container {
        margin-left: auto; /*将搜索框推到右侧*/
    }

    #subject .search-form {
        display: inline-flex;
        width: 20vw;
        margin-right: 5px;
        justify-content: flex-end;
    }


    #subject .search-input {
        font-size: 13px;
        height: 7vh;
        line-height: 6.6vh;
        flex: 1;
        margin: 0 auto;
    }

    /*输入框获得焦点时的颜色*/
    .el-input {
        --el-input-focus-border-color: #f13b82;
        height: 31px;
        width: 300px;
        margin-top: 1px;
    }

    /*//搜索按钮的颜色*/
    .el-button {
        background-color: #f13b82;
        border-color: pink;
        color: white;
        width: 50px;
        height: 32px;
        margin-top: 1px;
    }

    .el-button:hover {
        background-color: palevioletred;
        border-color: pink;
        color: white;
    }

    #subject .search-btn {
        font-size: 13px;
        background-color: rgba(255, 98, 242, 0.68);
        height: 7vh;
        line-height: 6.6vh;
        width: 1vw;
    }

    /*//商品分类的每个小盒子*/
    .goodsCategory {
        width: 40%;
        height: 24px;
        margin-left: 6px;
        margin-top: 5px;
        text-align: center;
        font-size: 15px;
        display: inline-block;
        color: rgba(16, 16, 16, 0.55);
    }
    .goodsCategory:hover{
        color: #f13b82;
        font-size: 16px;
    }

    /*以下为商品卡片部分*/
    #subject .goodsGroup {
        /*padding-top: 40px;*/
        display: flex;
        /*overflow-y: scroll;*/
        /*overflow-x: auto;*/
        flex-wrap: wrap; /*允许换行*/
        /*background-color: palegoldenrod;*/
        justify-content: left; /* 水平对齐方式 */
        align-items: flex-start; /* 垂直对齐方式 */
        padding-bottom: 20px;
        margin-left: 25px;
        margin-top: 5px;
    }

    /*卡片样式*/
    #subject .goodsCard {
        /*background-color: #FFC0CA;*/
        background-color: white;
        height: 30vw;
        width: 21vw;
        margin-left: 1vw;
        border: 1px solid transparent;
        margin-bottom: 20px;
        margin-right: 8px;
    }

    #subject .img-big {
        width: 21vw;
        height: 21vw;
        display: block;
        overflow: hidden;
    }

    /*商品图片*/
    #subject .good-picture {
        width: 21vw;
        height: 21vw;
        display: inline-block;
        transition: transform 0.3s ease;
    }

    #subject .good-picture:hover {
        width: 25vw;
        height: 25vw;
        display: inline-block;
        transition: 0.3s;
        /*transform: scale(1.2);*/
    }

    #subject .info-big {
        width: 20vw;
        height: 8vw;
    }

    /*放价格和价格描述*/
    #subject .money-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    /*价格标签*/
    #subject .money-tag {
        background-color: plum;
        border-radius: 6px;
        margin-left: 4px;
        padding-left: 4px;
        padding-right: 5px;
        font-size: 12px;
        font-family: 华文行楷;
        text-align: center;
    }

    /*价格样式*/
    #subject .good-money {
        font-size: 12px;
        font-weight: bold;
        padding-left: 5px;
        color: #f10160;
    }

    /*购物车按钮样式*/
    #subject .shopping-cart-btn {
        width: 4vw;
        height: 4vw;
        border-radius: 4vw;
        background-color: rgba(255, 197, 227, 0.68);
        border-color: #E13b82;
    }

    #subject .shopping-cart-btn:hover {
        background-color: rgba(255, 120, 199, 0.68);
        color: white;
    }

    /*商品名称样式*/
    #subject .good-name {
        height: 2vw;
        font-size: 11px;
        padding-left: 5px;
        padding-bottom: 3px;
        justify-items: center;
        overflow: hidden; /*多出的部分隐藏*/
        text-overflow: ellipsis;
        white-space: nowrap; /*防止换行*/
        font-family: 宋体;
        margin-top: 10px; /*如果不要购物车图标就加这个距离*/
    }

    /*标签与售出数量框样式*/
    #subject .tag-container {
        display: flex;
        align-items: center;
        border-top: 1px solid rgba(164, 165, 176, 0.68);
        padding-bottom: 3px;
    }

    #subject .tag {
        /*background-color: plum;*/
        border-radius: 4px;
        font-size: 9px;
        display: inline-block;
        margin-left: 5px;
        padding-left: 2px;
        padding-top: 3px;
        color: #8c939d;
        /*margin-bottom: 5px;*/
    }

    #subject .sell-count {
        display: inline-block;
        font-size: 10px;
        margin-right: 10px;
        margin-bottom: 4px;
        color: #cccccc;
        /*background-color: #8c939d;*/
    }

    /*左边的详情图片*/
    #subject .detail-picture {
        width: 30vw;
        height: 30vw;
    }

    /*右边的详情容器*/
    #subject .detail-container {
        display: inline-block;
        font-size: 15px;
        margin-left: 40px;
    }

    #subject .supplier-name {
        font-size: 10px;
        color: mediumpurple;
        font-weight: bold;
        padding-left: 5px;
    }

    #subject .detail-money {
        font-size: 20px;
        background-color: rgba(255, 28, 101, 0.68);
        color: white;
        font-weight: bold;
        width: 30vw;
    }


</style>
